
#include <string.h>
#include <stdbool.h>
#include "log/log2.h"
#include "id_card2.h"

unsigned SEGGER_RTT_Write(unsigned BufferIndex, const void *pBuffer, unsigned NumBytes);

#define RFID_ITF_ID_CARD_EN 1

#if RFID_ITF_ID_CARD_EN

#define HBIT_TIME          (SAMPLE_PER_BIT / 2)

#define GET_LEVEL(th, val) ((val) < (th) ? 1 : 0)

#define SAMPLE_NUM (SAMPLE_PER_BIT * 2)

//	static void card_data_decode(id_card_decode_t *decode, bool bit);
static int row_data_even_check(uint8_t *datas);
static int column_data_even_check(uint8_t *datas);
static void data_to_uid(uint8_t *uid, uint8_t *rf_data);

// 获取ID卡UID

typedef struct {
    uint16_t threshold; // 阈值

#if 0
    uint16_t max_val,min_val;
    uint16_t high_val,low_val;
#endif 

    uint8_t levelState;  // 电平解析状态
    uint8_t levelCur;    // 当前电平
    uint16_t levelWidth; // 当前电平的持续宽度

    uint8_t levelNew;     // 新电平
    uint8_t levelNewWith; // 新电平宽度

    /*解析电平*/
    uint8_t state;
    uint8_t level_cur;         // 当前电平
    uint16_t level_width;      // 连续电平宽度
    uint16_t fall_index_prev;  // 上次下降沿索引
    uint16_t fall_index_cur;   // 当前下降沿索引
    uint16_t rise_index;       // 当前上升沿索引
    uint16_t level_index;

    uint32_t levels;    // 电平缓存
    uint8_t levelCount; // 电平计数
    uint8_t syncCount;  // 数据帧同步计数

    uint8_t data[ID_DATA_BUF_LEN]; // 数据位
    uint8_t row;                   // 数据行
    uint8_t column;                // 数据列
    uint8_t even;                  // 偶数计数
    uint8_t bingo;                 // 数据接受完成标志
	uint16_t samples[SAMPLE_NUM];
//	    uint32_t error_count[5];
//	    uint8_t level_buf[512];
//	    uint32_t level_count;
} LFASKDecoder;

LFASKDecoder lfAskDecoder;

// data: 指向数组的指针
// n: 数组中的元素数量
static void shell_sort(uint16_t data[], int n)
{
    // 使用经典的 Knuth 步长序列: 1, 4, 13, 40, ...
    int gap = 1;
    while (gap < n / 3) {
        gap = gap * 3 + 1;
    }

    // 开始排序
    for (; gap > 0; gap /= 3) {
        // 对每个子序列进行插入排序
        for (int i = gap; i < n; i++) {
            int temp = data[i];
            int j;
            for (j = i; j >= gap && data[j - gap] > temp; j -= gap) {
                data[j] = data[j - gap];
            }
            data[j] = temp;
        }
    }
}


static uint16_t id_card_get_threshold3(LFASKDecoder *decoder, const uint16_t *data, uint16_t length)
{
//	    uint16_t samples[SAMPLE_NUM];
	uint16_t *samples = decoder->samples;
    memcpy(samples, data, sizeof(decoder->samples));
    // 1. 使用shell_sort对样本数组进行原地排序
    shell_sort(samples, SAMPLE_NUM);
    
    // 2. 找到下分位数 (20%) 和上分位数 (90%) 的索引
    int low_quartile_index  = SAMPLE_NUM * 20 / 100;
    int high_quartile_index = SAMPLE_NUM * 90 / 100;

    // 3. 获取稳定的高低电平值
    uint16_t stable_low  = samples[low_quartile_index];
    uint16_t stable_high = samples[high_quartile_index];
#if 0
    decoder->max_val = samples[SAMPLE_NUM-1];
    decoder->min_val = samples[0];
    decoder->high_val = stable_high;
    decoder->low_val = stable_low;
#endif 
    // 4. 计算并返回两者中间的阈值
    uint16_t threshold = stable_low + (stable_high - stable_low) * 80/ 100;
    // decoder->threshold = calculate_dynamic_threshold(samples, SAMPLE_NUM);
    decoder->threshold = threshold;
    return decoder->threshold;
}


void id_card_print_level_buf(void);
static int id_card_proc_data(LFASKDecoder *decoder, uint8_t bit)
{
    if (decoder->syncCount < ID_HEADER_BIT_NUM) {
        // 匹配头部，9个连续1
        if (bit) {
            decoder->syncCount++;
            if (decoder->syncCount == ID_HEADER_BIT_NUM) {
                // 匹配
                memset(decoder->data, 0, sizeof(decoder->data));
                decoder->row    = 0;
                decoder->column = 0;
                decoder->even   = 0;
                // uint16_t dbg = 0;
                // SEGGER_RTT_Write(1, &dbg, 2);
            }
            return 0;
        } else {
            // 未匹配
            decoder->syncCount = 0;
//	            decoder->error_count[2]++;
            return -1;
        }
    }
    // 处理数据
    decoder->data[decoder->column] <<= 1;
    decoder->data[decoder->column] |= bit ? 0x01 : 0x00;
    decoder->row++;
    if (bit) {
        decoder->even++;
    }

    if (decoder->row >= ID_DATA_BIT_NUM) {
        if ((decoder->even & 0x01) && (decoder->column < 10)) {
            // 奇数
            decoder->syncCount = 0;
            decoder->even      = 0;
//	            decoder->error_count[3]++;
            // SEGGER_RTT_Write(0, "odd: ", 5);
            // id_card_print_level_buf();
            return -2;
        }
        decoder->even = 0;
        decoder->row  = 0;
        decoder->column++;
    }

    if (decoder->column >= ID_DATA_BUF_LEN) {
        // 接收完成
        if (bit != 0) {
            decoder->syncCount = 0;
            decoder->row       = 0;
            decoder->column    = 0;
            return -3;
        } else {
            decoder->bingo = 1;
            return 1;
        }
    }

    return 0;
}
/*===========================================================================================*/
#include "Bit.h"
static void id_card_buf_level(LFASKDecoder *decoder, uint8_t level, uint8_t count)
{

    // for (uint32_t i = 0; i < count; i++) {
    //     if (decoder->level_count < 8 * 512) {
    //         BitBuffer_write(decoder->level_buf, decoder->level_count, level);
    //         decoder->level_count++;
    //     }
    // }
}

void id_card_print_level_buf(void)
{
    // if (lfAskDecoder.level_count > 0) {
    //     for (uint32_t i = 0; i < lfAskDecoder.level_count; i++) {
    //         const uint8_t bit = BitBuffer_read(lfAskDecoder.level_buf, i);

    //         SEGGER_RTT_Write(0, bit ? "1" : "0", 1);
    //     }
    //     SEGGER_RTT_Write(0, "\r\n", 2);
    //     lfAskDecoder.level_count = 0;
    // } else {
    //     // SEGGER_RTT_Write(0, "No Level Data", 14);
    // }
}

void id_card_level_buf_clear(void){
#if 0
    memset(lfAskDecoder.level_buf, 0, sizeof(lfAskDecoder.level_buf));
    lfAskDecoder.level_count = 0;
#endif 
}

/*===========================================================================================*/

//把电平添加到缓冲区
static void id_card_level_buf_add(LFASKDecoder *decoder, uint8_t level, uint16_t count)
{    
    if(!count){
        return ;
    }
    decoder->levels <<= count;
    if (level) {
        const uint32_t mask = ~(~0u << count);
        decoder->levels |= mask;
        // const static uint8_t bits1[8] = "11111111";
        // SEGGER_RTT_Write(0, bits1, count);
//	        id_card_buf_level(decoder, 1, count);
    } else {
        // const static uint8_t bits0[8] = "00000000";
        // SEGGER_RTT_Write(0, bits0, count);
//	        id_card_buf_level(decoder, 0, count);
    }
    decoder->levelCount += count;
}

//解析缓存的电平
static int id_card_decode_level(LFASKDecoder *decoder){
    int ret;
    uint32_t levels    = decoder->levels;
    uint8_t levelCount = decoder->levelCount;

    while (levelCount > 1) {
        // 获取比特电平
        uint8_t level = (levels >> (levelCount - 2)) & 0x03;
        if (level == 0x01) {
            ret = id_card_proc_data(decoder, 0);
            if (ret > 0) {
                return ret;
            }
            if (!ret) {
                levelCount--;
            }
        } else if (level == 0x02) {
            ret = id_card_proc_data(decoder, 1);
            if (ret > 0) {
                return ret;
            }
            if (!ret) {
                levelCount--;
            }
        } else {
//	            if(decoder->syncCount == ID_HEADER_BIT_NUM){
//					 SEGGER_RTT_Write(0, "sig: ", 5);
//					 id_card_print_level_buf();
//	            }
//	            decoder->error_count[4]++;
            decoder->syncCount = 0;            
        }

        levelCount--;
    }

    decoder->levels     = levels;
    decoder->levelCount = levelCount;
    return 0;
}

// --- 解码容差 ---
#define SAMPLES_PER_HALF_BIT     (SAMPLE_PER_BIT / 2.0f)
#define TIMING_TOLERANCE_PERCENT 20 // 20%的时间容差
#define TIMING_TOLERANCE_TICKS   (SAMPLES_PER_HALF_BIT * TIMING_TOLERANCE_PERCENT / 100)
#define SHORT_PULSE_MIN_TICKS    (SAMPLES_PER_HALF_BIT - TIMING_TOLERANCE_TICKS)
#define SHORT_PULSE_MAX_TICKS    (SAMPLES_PER_HALF_BIT + TIMING_TOLERANCE_TICKS)
#define LONG_PULSE_MIN_TICKS     (SAMPLE_PER_BIT - TIMING_TOLERANCE_TICKS * 2)
#define LONG_PULSE_MAX_TICKS     (SAMPLE_PER_BIT + TIMING_TOLERANCE_TICKS * 2)

// #define TIMING_LONG_LOW_TOLERANCE_PERCENT 25 // 25%的时间容差

// #define LONG_PULSE_LOW_MIN_TICKS     (SAMPLE_PER_BIT - SAMPLE_PER_BIT * TIMING_LONG_LOW_TOLERANCE_PERCENT / 100)
// #define LONG_PULSE_LOW_MAX_TICKS     (SAMPLE_PER_BIT + SAMPLE_PER_BIT * TIMING_LONG_LOW_TOLERANCE_PERCENT / 100)

static int is_short_plus(const uint16_t width)
{
    return SHORT_PULSE_MIN_TICKS <= width && width <= SHORT_PULSE_MAX_TICKS;
}

static int is_long_plus(const uint16_t width)
{
    return LONG_PULSE_MIN_TICKS <= width && width <= LONG_PULSE_MAX_TICKS;
}
static int id_card_convert_level4(LFASKDecoder *decoder, const uint16_t *data, uint16_t length)
{
    int ret = 0;
    const uint16_t *p    = data;
    const uint16_t *pend = data + length;
    const uint16_t th    = decoder->threshold;
    uint16_t width;
    uint8_t level;

    while (p < pend) {
        level = *p < th ? 1 : 0;
        p++;
        switch (decoder->state) {
            case 0: {
                // 查找头部的首个'1'电平
                if (level != 0) {
                    // 开始接收
                    decoder->state           = 1;
                    decoder->level_cur       = level;
                    decoder->level_width     = 1;
                    decoder->fall_index_prev = 0;
                    decoder->rise_index      = 0;
                    decoder->fall_index_cur  = 0;
                    decoder->level_index = 0;
                    decoder->levelCount = 0;
                    decoder->levels = 0;
                }
            } break;
            case 1:
            {
                // 接收数据
                decoder->level_index++;
                if (level == decoder->level_cur) {
                    // 接收相同电平
                    break;
                }

                // 检测到变化				
                if (level == 0) {
                    // 上升沿
                    decoder->rise_index = decoder->level_index;
                    decoder->level_cur = level;
                    break;
                }
                // 下降沿
                //由于信号下降沿比较陡峭，上升沿迟缓，因此通过检查两个下降沿的间隔来判断脉宽。
                decoder->level_cur = level;
                
                decoder->fall_index_prev = decoder->fall_index_cur;
                decoder->fall_index_cur  = decoder->level_index;
                width                    = decoder->fall_index_cur - decoder->fall_index_prev;
                uint16_t w1              = decoder->rise_index - decoder->fall_index_prev;
                uint16_t w2              = decoder->fall_index_cur - decoder->rise_index;

                if (width < LONG_PULSE_MIN_TICKS) {
                    // H/L
                    if (is_short_plus(w1)) {
                        // 接收0电平
                        id_card_level_buf_add(decoder, 1, 1);
                    } else if (is_short_plus(w2)) {
                        // 接收1电平
                        id_card_level_buf_add(decoder, 0, 1);
                    }
                } else if (width < LONG_PULSE_MAX_TICKS) {
                    // HL
                    id_card_level_buf_add(decoder, 1, 1);
                    id_card_level_buf_add(decoder, 0, 1);

                } else if (width < LONG_PULSE_MAX_TICKS + SAMPLES_PER_HALF_BIT) {
                    if (is_short_plus(w1)) {
                        // HLL
                        id_card_level_buf_add(decoder, 1, 1);
                        id_card_level_buf_add(decoder, 0, 2);
                    } else {
                        // HHL
                        id_card_level_buf_add(decoder, 1, 2);
                        id_card_level_buf_add(decoder, 0, 1);
                    }
                } else if (width < LONG_PULSE_MAX_TICKS + SAMPLE_PER_BIT) {
                    // HHLL
                    id_card_level_buf_add(decoder, 1, 2);
                    id_card_level_buf_add(decoder, 0, 2);
                } else {
                    uint16_t cnt = (w1 + HBIT_TIME / 4) / HBIT_TIME;
                    id_card_level_buf_add(decoder, 1, cnt);
                    cnt = (w1 + HBIT_TIME / 4) / HBIT_TIME;
                    id_card_level_buf_add(decoder, 0, cnt);
                }

                // id_card_level_buf_add不返回解码完成标志，如需判断请在此处添加相关逻辑

            } break;
        }
    }
    return 0;
}

int id_card_data_decode3(uint16_t *data, uint16_t len)
{
	uint16_t count = len / SAMPLE_NUM;
	
	if(len % SAMPLE_NUM){
		LOG2_ERR("data len %u is not mult of %u", len, SAMPLE_NUM);
		return -1;
	}
	
	for(int i = 0; i < count; i++){
	    /*
	    1.计算电平阈值
	    采样率经过合并后，为125K，以最大64分频，则一个bit为64个采样点，为防止跨bit采集都在低电平，因此取128个样点的均值为电平阈值。
	    */
	    uint16_t th = id_card_get_threshold3(&lfAskDecoder, data, SAMPLE_NUM);
	    if (th == 0) {
	        return -2;
	    }
	    /*
	    2.信号周期检测
	    检测信号的上升沿和下降沿，计算高电平或低电平的时间t，把电平转换为bit并缓存。
	    */
	    // 2.信号周期检测
	    // 检测信号的上升沿和下降沿，计算高电平或低电平的时间t，把电平转换为bit并缓存。
	    id_card_convert_level4(&lfAskDecoder, data, SAMPLE_NUM);
		data += SAMPLE_NUM;
	}
    /*
    3.数据解码
    高电平为1，低电平为0。
    a.若出现大于等于2个的连续0或1，则重新开始解码。保留一个电平，与后面的电平组合再解码。
    b.若相邻的两个电平相同，则丢弃在前的电平，剩下的电平与后面的电平组合判断。
    0x02 为 bit 1，0x01为bit0。高位先入。
    */
    return id_card_decode_level(&lfAskDecoder);
}


void id_card_reset(void)
{
    memset(&lfAskDecoder, 0, sizeof(lfAskDecoder));
}

int id_card_get(uint8_t uid[5])
{
    int ret                      = -1;
    const uint8_t invalid_uid[5] = {0x00};

    LFASKDecoder *decoder = &lfAskDecoder;
    if (decoder->bingo) {
        if (row_data_even_check(decoder->data) == 0) {
            if (column_data_even_check(decoder->data) == 0) {
                data_to_uid(uid, decoder->data);
                if (memcmp(uid, invalid_uid, sizeof(invalid_uid))){
                    ret = 0;
                }                    
            }
        }
        decoder->syncCount = 0;
        decoder->bingo     = 0;
    }
    return ret;
}


static int row_data_even_check(uint8_t *datas)
{
    uint8_t i, j;
    uint8_t tmp, even_check;

    for (i = 0; i < 10; i++) {
        tmp        = datas[i];
        even_check = 0;

        for (j = 0; j < 5; j++) {
            even_check ^= (tmp & 0x01); // LSB
            tmp >>= 1;                  // next bit
        }

        if (even_check != 0) // even check error
        {
            return -1;
        }
    }

    return 0;
}

static int column_data_even_check(uint8_t *datas)
{
    uint8_t i;
    uint8_t tmp, even_check = 0;

    for (i = 0; i < 11; i++) {
        tmp = (datas[i] & 0x1F) >> 1;
        even_check ^= tmp;
    }

    if (even_check != 0) {
        return -1;
    }

    return 0;
}

static void data_to_uid(uint8_t *uid, uint8_t *rf_data)
{
    uint8_t i;

    for (i = 0; i < 5; i++) {
        uid[i] = ((rf_data[(i << 1)] << 3) & 0xF0) +
                 ((rf_data[(i << 1) + 1] >> 1) & 0x0F);
    }
}

#endif
